#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <time.h>
#include <sys/timerfd.h>
#include "reactor.h"
Reactor::Reactor()
{
    /* 创建一个新的epoll */
    epoll_fds = epoll_create(100);
    quitloop = false;
}

Reactor::~Reactor()
{



}

/*　向reactor中注册一个新的监听通道　*/
void Reactor::addnewchannel(int fd,uint32_t events)
{
    struct epoll_event newev;//一个新的epoll事件
    newev.data.fd = fd;
    newev.events = events;
    epoll_ctl(epoll_fds, EPOLL_CTL_ADD, fd, &newev);//新增套接字
}

/* 添加一个定时器，在时间到达后执行回调函数,返回一个timerfd*/
int Reactor::addTimer(unsigned int time_ms, Eventcallback_t timerHandle)
{
    int timer_fd = timerfd_create(CLOCK_MONOTONIC, 0);
    struct itimerspec new_value;
    struct timespec outtime;
    outtime.tv_sec = (int)time_ms/1000;
    outtime.tv_nsec = (time_ms - outtime.tv_sec*1000)*1000000;
    new_value.it_interval = outtime;
    new_value.it_value = outtime;

    timerfd_settime(timer_fd, 0, &new_value, NULL);
    addnewchannel(timer_fd, EPOLLIN);
    setReadableCallback(timer_fd, timerHandle);
    return timer_fd;
}

//#define DEBUG_EPOLL
void Reactor::loop()
{
    int nfds = 0;
    int ready_fd = 0;
    while(!quitloop)
    {
        nfds = epoll_wait(epoll_fds,rp_events,20,-1);//等待事件发生
        if(nfds > 0)
        {
            #ifdef DEBUG_EPOLL
            printf("epoll_wait over %d\n",nfds);
            #endif
            for(int i = 0;i < nfds;i++)
            {
                if((ready_fd = rp_events[i].data.fd) < 0)
                {
                    printf("err in acceptor\n");
                    return;
                }
                if(rp_events[i].events == EPOLLIN)
                {   /* 调用事件处理回调函数　并将就绪事件的fd传出*/
                    readCallback_map.at(ready_fd)(ready_fd);
                }
                else if(rp_events[i].events == EPOLLOUT)
                {
                    writeCallback_map.at(ready_fd)(ready_fd);
                }
            }
        }
    }
}

